package com.ruoyi.socket.util;

import io.netty.buffer.ByteBuf;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/6/12
 *  @version: v1.0
 */
public class ByteBufStringUtils {


    /**
     * netty bytebuf转string
     *
     * @param buf
     * @return
     */
    public static String convertByteBufToString(ByteBuf buf) {

        String str = "";
        if (buf.hasArray()) { // 处理堆缓冲区
            str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
        } else { // 处理直接缓冲区以及复合缓冲区
            byte[] bytes = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(), bytes);
            str = new String(bytes, 0, buf.readableBytes());
        }
        return str;
    }


}
